package com.pug.user.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import xq.pug.common.exception.ServiceException;
import xq.pug.common.result.R;

/**
 * @author RenGaoshuai
 * @date 2023/7/13 10:28
 * @description 自定义切面，对controller层返回的R类增加traceId。
 * 使用环绕通知，也可以打印出所有的入参
 * 环绕通知：方法执行前会进入该方法，方法执行后也会进入该方法。
 */
@Slf4j
@Aspect
@Order(0)
@Component
public class TraceAspect {
    private static final String TRACE_ID = "traceId";


    @Around("execution(* com.pug.user.rest..*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String traceId = MDC.get(TRACE_ID);
        Object returnValue = null;
        try {
            returnValue = joinPoint.proceed();

            if (returnValue instanceof R) {
                ((R<?>) returnValue).setTraceId(traceId);
            }
        } catch (ServiceException e) {
            log.error("traceId[{}],err", traceId, e);
            returnValue = R.ofFail(e.getErrCode(), e.getMesg(), traceId);
        } catch (Exception e) {
            log.error("traceId[{}],err", traceId, e);
            returnValue = R.ofFail(-1, e.getMessage(), traceId);
        }

        return returnValue;
    }
}
